import {Button, message, Input, Drawer, Dropdown} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {useIntl, FormattedMessage, history, SelectLang, Link} from 'umi';
import ProTable from '@ant-design/pro-table';
import {ProFormGroup, ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import ProForm from '@ant-design/pro-form'
import {generateSuffix, getPrefix, updateUser, currentUser} from '@/services/doa/irs'
import ProCard from "@ant-design/pro-card";
import {useModel} from "@/.umi/plugin-model/useModel";
import BDStorageUtils from "@/utils/BDStorageUtils";

const PerInfoAdmin = () => {

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const [suffixValue, setSuffixValue] = useState("suffix")
  const [repoSuffix, setRepoSuffix] = useState("repoSuffix")
  const [prefixValue, setPrefixValue] = useState("prefix")
  const [submittedValue, setSubmittedValue] = useState({})
  const {initialState} = useModel('@@initialState');
  const [preview, setPreview] = useState([{}, {}, {}, {}, {}])
  const actionRef = useRef();


  //使用useEffect来解决setState状态信息更新不及时的问题
  useEffect(() => {
    updatePreview()
    actionRef.current.reloadAndRest()
  }, [submittedValue])

  const formRef = useRef()

  const info = (msg) => {
    message.info(msg);
  };

  const deses = {
    "doi": "用户标识",
    "organization": "组织机构",
    "publicKey": "公钥",
    "suffix": "标识后缀",
  }

  const updatePreview = () => {
    const data = []
    for (const key in submittedValue) {
      if (submittedValue[key] == null)
        continue
      data.push({key: key, value: submittedValue[key], 'des': deses[key]})
    }
    setPreview(data)
  }

  useEffect(async () => {
    const doi = initialState.doi != null ? initialState.doi : BDStorageUtils.getUsers().doi
    console.log("user doi:" + doi)

    await getPrefix().then((res) => {
      if (res?.success) {
        setPrefixValue(res.data)
      }
    })

    currentUser({"doi": doi}).then((res) => {
      if (res?.success) {
        setSubmittedValue(res?.data)
        formRef?.current?.setFieldsValue(res?.data)
      }
    })
  }, [])


  const onGenerateDoi = async () => {
    let prefixFromServer = ''
    await getPrefix().then((res) => {
      if (res?.success) {
        setPrefixValue(res.data)
        prefixFromServer = res.data
      }
    })

    generateSuffix({"type": "doip"}).then((data) => {
      setRepoSuffix(data.data);
    })
  }

  const onGenerateSuffix = async () => {

    let prefixFromServer = ''
    await getPrefix().then((res) => {
      if (res?.success) {
        setPrefixValue(res.data)
        prefixFromServer = res.data
      }
    })

    generateSuffix({"type": "dou"}).then((data) => {
      setRepoSuffix(data.data);

      const tmp = {...submittedValue}
      tmp.suffix = data.data
      tmp.doi = prefixFromServer + '/' + data.data

      setSubmittedValue(tmp)
    })
  }
  const onValuesChanged = (values) => {
    console.log(values)
    setSuffixValue(values?.suffix)
    setSubmittedValue({...values, 'doi': prefixValue + '/' + suffixValue})
  }

  const onSubmit = () => {
    updateUser(submittedValue).then((response) => {
      if (response?.success == true) {
        info(response?.data)
      }
    })
  }

  const columns = [
    {
      dataIndex: 'key',
      title: '键',
    },
    {
      dataIndex: 'value',
      title: '值',
    },
    {
      dataIndex: 'des',
      title: '描述',
    }
  ];

  return (
    <>
      <ProCard colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
        <ProForm
          formRef={formRef}
          onValuesChange={(_, values) => {
            onValuesChanged(values);
          }}
          submitter={{
            searchConfig: {
              submitText: intl.formatMessage({
                id: 'pages.PerInfoManagement.update',
                defaultMessage: '更新用户信息',
              }),
            },
          }}
          onFinish={async (values) => {
            handleSubmit(values);
          }}
          onFinish={async (values) => {
            onSubmit()
            console.log(values);
          }}
        >
          <ProFormText width="md" placeholder="请输入组织机构名称" name="organization"
                       rules={[
                         {
                           required: true,
                         }]}/>
          <ProFormGroup>
            <ProFormText width="md" placeholder="请输入后缀" name="suffix"
                         rules={[
                           {
                             required: true,
                           }]}/>
            <Button type="primary" onClick={onGenerateSuffix}>自动生成</Button>
          </ProFormGroup>
          <ProFormGroup>
            <ProFormTextArea width="md" autoSize={true} placeholder="导入JWK格式的公钥" name="publicKey"
                             rules={[
                               {
                                 required: true,
                               }]}/>
            <Button type="primary" onClick={onGenerateSuffix}>自动生成</Button>
          </ProFormGroup>
        </ProForm>
      </ProCard>
      <ProCard colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
        <h3>用户信息预览</h3>
        <ProTable
          columns={columns}
          request={(params, sorter, filter) => {
            return Promise.resolve({
              data: preview,
              success: true,
            });
          }}
          actionRef={actionRef}
          rowKey="preview"
          pagination={
            false
          }
          options={false}
          toolBarRender={false}
          search={false}
        />
      </ProCard>

      <ProCard title={"生成仓库标识"}>
        {"生成仓库标识："}{prefixValue+"/"+repoSuffix}
        <Button type="primary" onClick={onGenerateDoi}>自动生成</Button>
      </ProCard>
    </>
  );
};

export default PerInfoAdmin;
